package com.mj.mes.system;

import com.mj.mes.system.SysResource.SysResource;
import com.mj.mes.system.SysResource.SysResourceService;
import com.mj.mes.system.SysRole.SysRole;
import com.mj.mes.system.SysUser.SysUser;
import com.mj.mes.system.SysUser.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by ju on 2017/3/27.
 */
@Controller
public class Login {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysResourceService sysResourceService;

    @RequestMapping("")
    public String login(SysUser sysUser) {
        return "login";
    }

    @RequestMapping("/login")
    public String helloHtml(SysUser sysUser, Model model, HttpServletRequest request) {
//        File file=new File("");
        String msg = "pwdOK";
        //判断密码是否为初始密码
        if ("123456".equals(sysUser.getUserPassword())) {
            msg = "pwdNOK";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        subject.login(token);
        token.setRememberMe(true);
        sysUser = sysUserService.findOne(sysUser.getUserName());
        session.setAttribute("id", sysUser.getId());
        session.setAttribute("userName", sysUser.getUserName());
        model.addAttribute("msg", msg);
        logger.info(sysUser.getUserName() + " Login Sussesful");
        return "index";
    }

    /**
     * 异步加载一级菜单
     *
     * @param id
     * @return
     */
    @RequestMapping("findLevelOneByUserId")
    @ResponseBody
    private List<SysResource> leftLevelOne(String id) {
        Set<SysResource> set = new HashSet<>();
        SysUser sysUser = sysUserService.findOne(Long.valueOf(id));
        for (SysRole role : sysUser.getRoles()) {
            for (SysResource sysResource : role.getSysresources()) {
                if (sysResource.getSysResource() == null && sysResource.getResourceAvailable() !=1) {
                    set.add(sysResource);
                }
            }
        }
        List<SysResource> list = new ArrayList<>();
        list.addAll(set);
        Collections.sort(list,new Comparator<SysResource>() {
            @Override
            public int compare(SysResource o1, SysResource o2) {
                return o1.getId()<o2.getId() ? -1 :1;
            }
        });
        return list;
    }

    @RequestMapping("findLevelTwo")
    @ResponseBody
    private List<SysResource> leftLevelTwo(String parentName,String userId) {
        //一级菜单下的所有二级菜单
        List<SysResource> list = new ArrayList<SysResource>();
        //该用户应该拥有的二级菜单
        Set<SysResource> ownSecondSet = new HashSet<>();
        //该用户所拥有的所有菜单，包括一级、二级菜单
        Set<SysResource> ownSet = new HashSet<>();
        try {
            SysUser sysUser =sysUserService.findOne(Long.valueOf(userId));
            //用户对应的角色
            for (SysRole sysRole:sysUser.getRoles()) {
                //角色对应的权限
                for (SysResource sysResource:sysRole.getSysresources()) {
                    ownSet.add(sysResource);
                }
            }
            SysResource parentSysResource = sysResourceService.findByResourceName(parentName);
            list = sysResourceService.findBySysResource(parentSysResource);
           //提取应该有的二级菜单
            for (SysResource sysResource:list) {
                if(ownSet.contains(sysResource) && sysResource.getResourceAvailable() != 1){
                    ownSecondSet.add(sysResource);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<SysResource> listSecondSet = new ArrayList<SysResource>();
        listSecondSet.addAll(ownSecondSet);
        Collections.sort(listSecondSet,new Comparator<SysResource>() {
            @Override
            public int compare(SysResource o1, SysResource o2) {
                return o1.getId()<o2.getId() ? -1 :1;
            }
        });
        return listSecondSet;
    }

    @RequestMapping("loginOut")
    public String loginOut() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "login";
    }
}
